package com.ck.web.manager.ldap;

import com.novell.ldap.*;

import java.io.UnsupportedEncodingException;

/**
 * @author ChengK
 * @version Id: LDAPAddEntry.java v 0.1 2017/07/10 16:02 ChengK Exp $$
 */
public class LDAPAddEntry {

    /**
     *
     * @param args
     */
    public static void main(String[] args) {

        String ldapHost = "192.168.161.161";
        String loginDN = "cn=Manager,dc=demo,dc=com";
        String password = "secret";
        String containerName = "dc=demo,dc=com";

        for(int i=1000;i<10000;i++){
            System.out.println("===================="+i+"=======================");
            int ldapPort = LDAPConnection.DEFAULT_PORT;
            int ldapVersion = LDAPConnection.LDAP_V3;
            LDAPConnection lc = new LDAPConnection();
            LDAPAttributeSet attributeSet = new LDAPAttributeSet();

            attributeSet.add(new LDAPAttribute("objectclass", "inetOrgPerson"));
            attributeSet.add(new LDAPAttribute("cn", "testCn"+i));
            attributeSet.add(new LDAPAttribute("sn", "Sun"+i));
            attributeSet.add(new LDAPAttribute("mail", "sjsky007@gmail.com"+i));
            attributeSet.add(new LDAPAttribute("labeledURI", "http://www.test.com"+i));
            attributeSet.add(new LDAPAttribute("userPassword", "testPwd"+i));
            attributeSet.add(new LDAPAttribute("uid", "uid"+i));
            String dn = "uid=uid"+i+",ou=Employees,"+containerName;
            LDAPEntry newEntry = new LDAPEntry(dn, attributeSet);
            try {
                lc.connect(ldapHost, ldapPort);
                lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
                System.out.println("login ldap server successfully.");
                lc.add(newEntry);
                System.out.println("Added object: " + dn + " successfully.");
            } catch (LDAPException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                System.out.println("Error: " + e.toString());
            } finally {
                try {
                    if (lc.isConnected()) {
                        lc.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
